﻿using Avalon.Core.Providers;
using System.Web.Mvc;
using System.Web.Routing;

namespace Avalon.Core.MVC {
    /// <summary>
    /// The avalon controller factory
    /// </summary>
    public class AvalonControllerFactory : DefaultControllerFactory {

        /// <summary>
        /// Create a controller, either from the MVC stack or from the Avalon statck.
        /// </summary>
        /// <param name="requestContext">The current request context</param>
        /// <param name="controllerName">The name of the controller</param>
        /// <returns>A controller</returns>
        public override IController CreateController(RequestContext requestContext, string controllerName) {
            //register the new request with the provider container.
            ProviderContainer.Current.InitializeContainer(requestContext);

            IControllerProvider controllerProvider = ProviderContainer.Current.ControllerProvider;
            IControllerDescriptor descriptor = controllerProvider.CreateController();
            ContextProvider.ControllerDescriptor = descriptor;

            return descriptor.Controller;
        }
    }
}
